package jsf;

import bean.BuyManager;
import bean.UserManager;
import java.io.Serializable;
import java.util.Date;
import jpa.entities.ItemPedido;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jpa.session.ItemPedidoFacade;

import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import jpa.session.PedidoFacade;
import jpa.session.ProdutoFacade;
import br.com.uol.pagseguro.domain.*;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.Endereco;
import jpa.entities.ItemPedidoPK;
import jpa.entities.Pedido;
import jpa.entities.Produto;
import jpa.entities.Usuario;
import jpa.entities.UsuarioCli;

@ManagedBean(name = "itemPedidoController")
@SessionScoped
public class ItemPedidoController implements Serializable {

    private ItemPedido current;
    private BuyManager compras;
    private String clean = null;
    private DataModel items = null;
    @EJB
    private jpa.session.ItemPedidoFacade ejbFacade;
    @EJB
    private jpa.session.PedidoFacade ejbPedidoFacade;
    @EJB
    private jpa.session.ProdutoFacade ejbProdutoFacade;
    private UserManager login = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Endereco endereco;
    private Usuario usuario;
    private UsuarioCli usuarioCli;
    private String urlPagSeguro = null;

    public String getUrlPagSeguro() {
        return urlPagSeguro;
    }

    public ItemPedidoController() {
        login = (UserManager) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userManager");
    }

    public String getClean() {

        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("itemPedidoController");
        return "";
    }

    public Endereco getEndereco() {
        if (usuario != null) {
            return usuarioCli.getEnderecoCollection().iterator().next();
        }
        return null;
    }

    public Usuario getUsuario() {

        if (usuario == null) {
            usuario = login.getUser();
            usuarioCli = usuario.getUsuarioCliCollection().iterator().next();
        }
        return usuario;

    }

    public ItemPedido getSelected() {
        if (current == null) {
            current = new ItemPedido();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ItemPedidoFacade getFacade() {
        return ejbFacade;
    }

    private PedidoFacade getPedidoFacade() {
        return ejbPedidoFacade;
    }

    private ProdutoFacade getProdutoFacade() {
        return ejbProdutoFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findAllPendentes(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (ItemPedido) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new ItemPedido();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ItemPedidoCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String createPedidos() {
        PaymentRequest paymentRequest = null;


        Endereco endereco = null;
        try {

            HttpServletResponse response = null;
            endereco = new Endereco();
            paymentRequest = new PaymentRequest();
            paymentRequest.setCurrency(Currency.BRL);
            endereco = login.getUser().getUsuarioCliCollection().iterator().next().getEnderecoCollection().iterator().next();
            for (ItemPedido item : compras.getList()) {

                paymentRequest.addItem(
                        item.getProduto().getIdProduto().toString(),
                        item.getProduto().getDescricao(),
                        new Integer(item.getQtd()),
                        item.getProduto().getValorUnitario().setScale(2),
                        new Long(0),
                        null);
                this.baixaPedido(item);


            }
            paymentRequest.setReference("REF6666");

            paymentRequest.setShippingAddress(
                    "BRA",
                    endereco.getUf(),
                    "Belo Horizonte",
                    endereco.getBairro(),
                    endereco.getCep(),
                    endereco.getLogradouro(),
                    "566",
                    "n/a");

            paymentRequest.setShippingType(ShippingType.SEDEX);

            paymentRequest.setSender(login.getUser().getNome() + " Sobenome",
                    login.getUsername(),
                    "31",
                    "25529191");


            compras.removeAll();
            URL paymentURL = paymentRequest.register(new AccountCredentials("cacahm@hotmail.com", "1BE36B687C3D41439802F31C6C45D2D2"));
            urlPagSeguro = paymentURL.toString();
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://localhost:8080/LaCruz_v2/faces/compraConcluida.xhtml");


            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ItemPedidoCreated"));
            return "ListCliente";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    private Boolean baixaPedido(ItemPedido item) throws Exception {
        Pedido pedido = new Pedido();
        Produto produto = new Produto();
        ItemPedidoPK itemPK = new ItemPedidoPK();
        try {
            //cria o pedido
            pedido.setUsuario(login.getUser());
            getPedidoFacade().create(pedido);

            //cria o item de pedido
            itemPK.setPedidoidPedido(pedido.getIdPedido());
            itemPK.setProdutoidProduto(item.getProduto().getIdProduto());
            item.setItemPedidoPK(itemPK);
            item.setPedido(pedido);
            item.setStatusPedido('A');
            getFacade().create(item);

            //baixa no estoque
            produto = item.getProduto();
            produto.setQuantidade(produto.getQuantidade() - item.getQtd());
            getProdutoFacade().edit(produto);
           return true;
        } catch (Exception e) {
            throw e;
        }

    }

    public String prepareEdit() {
        current = (ItemPedido) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ItemPedidoUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (ItemPedido) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String aprove() {
        current = (ItemPedido) getItems().getRowData();
        current.setStatusPedido('A');
        current.setDataBaixa(new Date());
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        update();
        recreateModel();
        return "List";
    }

    public String reprove() {
        current = (ItemPedido) getItems().getRowData();
        current.setStatusPedido('R');
        current.setDataBaixa(new Date());
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        update();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ItemPedidoDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findAllPendentes(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public DataModel getPedidos() {

        compras = (BuyManager) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("buyManager");
        items = new ListDataModel(compras.getList());
        return items;
    }

    public String removePedido(ItemPedido item) {
        try {

            compras.destroy(item.getProduto());
            recreatePedidos();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ItemPedidoDeleted"));
            return "ListCliente";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePedidos() {
        compras = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = ItemPedido.class)
    public static class ItemPedidoControllerConverter implements Converter {

        private static final String SEPARATOR = "#";
        private static final String SEPARATOR_ESCAPED = "\\#";

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ItemPedidoController controller = (ItemPedidoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "itemPedidoController");
            return controller.ejbFacade.find(getKey(value));
        }

        jpa.entities.ItemPedidoPK getKey(String value) {
            jpa.entities.ItemPedidoPK key;
            String values[] = value.split(SEPARATOR_ESCAPED);
            key = new jpa.entities.ItemPedidoPK();
            key.setPedidoidPedido(Integer.parseInt(values[0]));
            key.setProdutoidProduto(Integer.parseInt(values[1]));
            return key;
        }

        String getStringKey(jpa.entities.ItemPedidoPK value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value.getPedidoidPedido());
            sb.append(SEPARATOR);
            sb.append(value.getProdutoidProduto());
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ItemPedido) {
                ItemPedido o = (ItemPedido) object;
                return getStringKey(o.getItemPedidoPK());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ItemPedidoController.class.getName());
            }
        }
    }
}
